$(function () {
    /**
     * 获取两个时间之间的间隔天数
     * @param  Date comparand 被比较的时间对象
     * @example
     * var diffDays = new Date().getDays(getDate('2015-12-01'));
     * @return integer
     */
    Date.prototype.getDays = function (comparand) {
        var thisTime = this.getTime();
        var comparandTime = comparand.getTime();
        return parseInt((thisTime - comparandTime) / 86400000);
    };
    toggleLoading(true);
    var getParams = getArgs();
    var currentHotel = getParams.hotel;
    var orderNumber = getParams.no;
    var originalHref = $('#doc-header a').attr('href');
    $('#doc-header a').attr('href', originalHref + '?hotel=' + currentHotel);
    originalHref = $('#doc-content a').attr('href');
    $('#doc-content a').attr('href', originalHref + '?hotel=' + currentHotel);
    var isWechatBrowser = function() {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
            return true;
        } else {
            return false;
        }
    };
    $('#orderBookingContainer .speedpay').on('click',function(){  
        var params = {
            hotel: currentHotel,
        };
        ajaxRequest('/Home/Hotel/payInfo', params, 'POST', function(data) {
            var alipay = data.data.ali == 0;
            var vipcardpay = data.data.vipcardpay == 1;
            var wechatpay = data.data.wechat == 0;
            var wechat = 0;
            if(wechatpay && vipcardpay){
                wechat = 2;
            };
            var pay = 1;
            if(alipay && vipcardpay){
                pay = 2;
            };              
            if(isWechatBrowser()){    
                ajaxRequest('/Home/Order/getWechatInfo', {
                    'hotelId':currentHotel
                }, 'post', function (data) {
                    var ai = data.data.ai;
                    var asc = data.data.asc;
                    window.location.href = 'http://cz.uclbrt.com/Wechat/WechatLoginPage/auth.html?type=mz&hotel=' + currentHotel + '&no=' + orderNumber + '&orderHotel=' + window.currentOrder.orderHotel + '&back=/Home/PayPage/speedpay.html&pay='+wechat+'&ai='+ai+'&asc='+asc;
                }, null);    
            }else{
                window.location.href = '/Home/payPage/speedpay?hotel='  + currentHotel + '&no=' + orderNumber + '&orderHotel=' + window.currentOrder.orderHotel+ '&pay='+pay;            
            }            
        }, function(error) {});          
    })

    toggleLoading(false);

    toastr.options = {
        "newestOnTop": false,
        "timeOut": 1500,
        "extendedTimeOut": 0,
        "escapeHtml": true,
        "positionClass": "toast-bottom-center"
    };
    if (currentHotel === undefined || currentHotel === '') {
        toastr.error(lang('toastr.grogshop'));
        return;
    }
    if (orderNumber === undefined || orderNumber === '') {
        toastr.error(lang('toastr.order'));
        return;
    }
    var today = $('#doc').data('today');
    var todayDate = getDate(today);

    var orderStatusConstant = {
        'booked': 0,
        'paied': 1,
        'checkined': 2,
        'checkouted': 3,
        'cancelled': 4,
        'outdated': 5,
        'needOut': 6,
    };

    var orderStatusNameConstant = [lang('status.reserve'), lang('status.payment'), lang('status.checkIn'), lang('status.checkOut'), lang('status.canceled'), lang('status.expired'), lang('status.needOut')];
    var orderRefundStatusConstant = {
        'default': 0,
        'applying': 1,
        'rejected': 3
    };
    var documentBody = $('#doc-body');
    var refundModal = $('#refundModal');
    var checkOutModal = $('#checkOutModal');
    documentBody.find('.order-number').html(orderNumber);
    var refreshDocument = function (orderInfo) {
        $('.checkedRoomName').html('');
        documentBody.find('.order-hotel-name').html(orderInfo.hotelName);
        documentBody.find('.order-hotel-address').html(orderInfo.address);
        documentBody.find('.order-room-type').html(orderInfo.roomTypeName);
        documentBody.find('.order-room-name').html(orderInfo.roomName);
        documentBody.find('.order-checkout-date').html(orderInfo.endDate);
        if (orderInfo.hour > 0) {
            documentBody.find('.order-checkin-date').html(orderInfo.startDate.substr(11));
            documentBody.find('.order-night').html(orderInfo.hour + lang('hour'));
        } else if (orderInfo.month > 0) {
            documentBody.find('.order-checkin-date').html(orderInfo.startDate.substr(0,10));
            documentBody.find('.order-night').html(orderInfo.month + lang('month'));
        } else {
            documentBody.find('.order-checkin-date').html(orderInfo.startDate.substr(0,10));
            documentBody.find('.order-night').html(orderInfo.night + lang('nights'));
        }
        documentBody.find('.order-price').html(orderInfo.price);
        if(parseFloat(orderInfo.charityPrice) == 0){
            refundModal.find('.isCharityPrice').addClass('hidden');
            checkOutModal.find('.isCharityPrice').addClass('hidden');
            documentBody.find('.order-charityPrice').html(orderInfo.charityPrice).closest('.fixed-left-container').addClass('hidden');
        }else{
            refundModal.find('.isCharityPrice').removeClass('hidden');
            checkOutModal.find('.isCharityPrice').removeClass('hidden');
            documentBody.find('.order-charityPrice').html(orderInfo.charityPrice).closest('.fixed-left-container').removeClass('hidden');
        }
        if(parseFloat(orderInfo.couponPrice) == 0){
            documentBody.find('.coupon-price').html(orderInfo.couponPrice).closest('.fixed-left-container').addClass('hidden');
        }else{
            documentBody.find('.coupon-price').html(orderInfo.couponPrice).closest('.fixed-left-container').removeClass('hidden');
        }        
        if(parseFloat(orderInfo.receipt) > 0 ){
            documentBody.find('.orderPrice').addClass('hidden');
            documentBody.find('.receivePrice').removeClass('hidden');
            documentBody.find('.order-receive').html(orderInfo.receipt);
        }else{
            documentBody.find('.orderPrice').removeClass('hidden');
            documentBody.find('.receivePrice').addClass('hidden');
        }
        documentBody.find('.order-deposit').html(orderInfo.deposit ? orderInfo.deposit: 0);
        documentBody.find('.order-total').html(orderInfo.orig);
        documentBody.find('.order-payable').html(orderInfo.payPagePrice);
        if(parseFloat(orderInfo.minusprice) >0 ){
            $('.payable').find('.fixed-left').text(lang('discountPrice'));
        }else{
            if(parseInt(orderInfo.payPagePrice) != parseInt(orderInfo.orig)){
                $('.payable').find('.fixed-left').text(lang('vip.price'));
            }            
        }

        var isBookedUser = '';
        if(orderInfo.currentUserId == orderInfo.bookPerson){
            isBookedUser = true;
        }else{
            isBookedUser = false;
        }
        var status = [];
        if (orderInfo.user !== undefined) {
            var orderInfoInfo = orderInfo.user;
            var roomInfoHTML = '';
            var roomCheckedHTML = '';
            var templateAddRoomChecked = $($('#templateRoomChecked').clone().html());
            var currentOrderRefundStatus = parseInt(orderInfo.refundStatus);
            var roomId = [];
            for(var i=0;i<orderInfoInfo.length;i++){
                var templateAddRoomInfo = $($('#templateRoomInfo').clone().html());
                templateAddRoomInfo.find('.order-status-container .orderCheckin').removeClass('hidden');
                var currentOrderStatusInfo =parseInt(orderInfoInfo[i].status);
                var realStatusName = orderStatusNameConstant[currentOrderStatusInfo];
                if (currentOrderStatusInfo === orderStatusConstant.paied) {
                    if (currentOrderRefundStatus === orderRefundStatusConstant.applying) {
                        realStatusName += ' -'+lang('applyRefund');
                    }
                    if (currentOrderRefundStatus === orderRefundStatusConstant.rejected) {
                        realStatusName += ' -'+lang('rejectRefund');
                    }
                }
                if(orderInfoInfo[i].status == orderStatusConstant.paied){
                    roomId.push(orderInfoInfo[i].orderRoomId);
                }              
                status.push(parseInt(orderInfoInfo[i].status));
                templateAddRoomInfo.find('.order-status').html(realStatusName);
                templateAddRoomInfo.find('.order-user-name').html(orderInfoInfo[i].name);
                templateAddRoomInfo.find('.orderRoomCard').attr('href', '/Home/RoomPage/index' + '?hotel=' + currentHotel + '&no=' + orderInfoInfo[i].orderRoomId+ '&UserId=' + orderInfoInfo[i].bookUserId);
                templateAddRoomInfo.find('.order-user-mobile').html('+'+orderInfoInfo[i].areaCode+"&nbsp;"+ orderInfoInfo[i].mobile);
                templateAddRoomInfo.find('.order-room-name').html(orderInfoInfo[i].roomName);
                if(orderInfoInfo[i].identity){
                    templateAddRoomInfo.find('.order-user-idCard').html(orderInfoInfo[i].identity);
                }
                templateAddRoomInfo.find('.orderCheckin').attr({
                        'bookUserId':orderInfoInfo[i].bookUserId,
                        'status':parseInt(orderInfoInfo[i].status),
                        'canGetCard':orderInfoInfo[i].canGetCard,
                        'index':i,
                        'room':orderInfoInfo[i].orderRoomId,
                        'checkinEnable':orderInfoInfo[i].checkinEnable
                });
                templateAddRoomInfo.find('.fillIdentity').attr('orderuserid',orderInfoInfo[i].orderUserId);
                templateAddRoomInfo.find('.order-user-name').attr({'bookPerson':orderInfoInfo[i].bookPerson});
                templateAddRoomChecked.find('input').attr({"room":orderInfoInfo[i].orderRoomId,'index':i});
                templateAddRoomChecked.find('.roomName').text(lang('room')+'：'+orderInfoInfo[i].roomName+'('+realStatusName+')');
                roomInfoHTML += templateAddRoomInfo.prop('outerHTML');
                roomCheckedHTML += templateAddRoomChecked.prop('outerHTML');
            }
            $('#addRoomInfoHTML').append(roomInfoHTML);
            $('.checkedRoomName').append(roomCheckedHTML);
        }
        $('#orderCheckin').data("orderRoomId",roomId);
        var currentOrderStatus = '';
        var currentOrderStatusOther = '';
        var nary = status.sort();
        if(nary.length>1){
            for(var i = 0; i < nary.length - 1; i++){
                currentOrderStatus = nary[0];
                currentOrderStatusOther = nary[0];
                if(nary[i] !== nary[i+1]){
                    currentOrderStatus = '';
                    break;
                } 
                if(nary[i] == orderStatusConstant.paied){
                    currentOrderStatusOther == orderStatusConstant.paied;
                }            
            }            
        }else{
            currentOrderStatus = nary[0];
            currentOrderStatusOther = nary[0];
        }            
        var orderCheckin = $('.orderCheckin');
        var orderRoomCard = $('.orderRoomCard');
        var noOrderRoomCard = $('.noOrderRoomCard');
        var orderusername = $('.order-user-name');
        var checkedRoomName = $('.checkedRoomName label');
        var orderContainer = $('#orderBookingContainer');
        var orderCheckOutContainer = $('#orderCheckOutContainer');
        var orderCheckInContainer = $('#orderCheckInContainer');
        var contactShopkeeper = $('.contact-the-shopkeeper');
        var linePayPrompt = $('.line-pay-prompt');
        var payable = $('.payable');
        checkedRoomName.addClass('hidden');
        orderCheckin.addClass('hidden');
        orderRoomCard.addClass('hidden'); 
        orderContainer.addClass('hidden');
        orderCheckInContainer.addClass('hidden');
        orderCheckOutContainer.addClass('hidden');
        documentBody.find('.order-status').removeClass('active').removeClass('disabled');
        if(orderInfo.telephone != ''){
            contactShopkeeper.attr('href','tel:'+orderInfo.telephone);
        }else{
            contactShopkeeper.attr('href','tel:'+orderInfo.mobile);
        }
        switch (currentOrderStatusOther) {
            case orderStatusConstant.booked:
                payable.removeClass('hidden');
                if(isBookedUser == true){
                    orderContainer.removeClass('hidden');
                    if(orderInfo.status == 4){
                        orderContainer.addClass('hidden');
                    }
                    if(orderInfo.telephone != ''){
                        orderContainer.find('.line-cancel-service').attr('href','tel:'+orderInfo.telephone);
                    }else{
                        orderContainer.find('.line-cancel-service').attr('href','tel:'+orderInfo.mobile);
                    }
                    if(orderInfo.isOffline == true){
                        linePayPrompt.removeClass('hidden');
                        orderContainer.find('.speedpay').addClass('hidden');
                        orderContainer.find('.line-from-service-before').addClass('hidden');
                        orderContainer.find('.line-from-service').removeClass('hidden');
                        contactShopkeeper.addClass('hidden');
                    }else if(orderInfo.isOffline == false){
                        linePayPrompt.addClass('hidden');
                        contactShopkeeper.removeClass('hidden');
                        orderContainer.find('.line-from-service-before').removeClass('hidden');
                        orderContainer.find('.speedpay').removeClass('hidden');
                        orderContainer.find('.line-from-service').addClass('hidden');
                    }
                    documentBody.find('.order-reserved').html(orderInfo.orderOutdateTime);
                    documentBody.find('.order-reserved-container').removeClass('hidden');    
                }
                break;
            case orderStatusConstant.paied:
                if(isBookedUser == true){
                    checkedRoomName.removeClass('hidden');
                    for(var i=0;i<orderCheckin.length;i++){
                        var status = orderCheckin.eq(i).attr('status');
                        var bookPerson = orderusername.eq(i).attr('bookPerson'); 
                        var canGetCard = orderCheckin.eq(i).attr('canGetCard');
                        if(bookPerson == 1 && status == orderStatusConstant.paied){
                            orderCheckInContainer.removeClass('hidden');
                        }
                        if(status== orderStatusConstant.checkined){
                            orderCheckOutContainer.removeClass('hidden');
                            checkedRoomName.eq(i).find('input').attr({'disabled':false,'checked':true});
                            checkedRoomName.eq(i).find('.roomName').removeClass('roomNameNoCheck');
                        }else{
                            checkedRoomName.eq(i).find('input').attr({'disabled':true,'checked':false});
                            checkedRoomName.eq(i).find('.roomName').addClass('roomNameNoCheck');
                        }
                        if(status== orderStatusConstant.paied){
                            orderCheckin.eq(i).removeClass('hidden');
                        }else if(status== orderStatusConstant.checkined){
                            if(canGetCard == 1){
                                orderRoomCard.eq(i).removeClass('hidden');
                            }else{
                                noOrderRoomCard.eq(i).removeClass('hidden');
                            }
                            
                        }                              
                    }                    
                }else{
                    for(var i=0;i<orderCheckin.length;i++){
                        var UserId = orderCheckin.eq(i).attr('bookUserId');
                        var canGetCard = orderCheckin.eq(i).attr('canGetCard');
                        var status = orderCheckin.eq(i).attr('status');
                        if(UserId == orderInfo.currentUserId){
                            if(status== orderStatusConstant.paied){
                                orderCheckin.eq(i).removeClass('hidden');
                            }else if(status== orderStatusConstant.checkined){
                                if(canGetCard == 1){
                                    orderRoomCard.eq(i).removeClass('hidden');
                                }else{
                                    noOrderRoomCard.eq(i).removeClass('hidden');
                                }
                                checkedRoomName.eq(i).removeClass('hidden').find('input').attr({'checked':true});
                                orderCheckOutContainer.removeClass('hidden');
                            }
                            break;
                        }
                    }
                }
                var nowDay = new Date().getTime();
                var startDiffToday = new Date(orderInfo.startDate.replace(/-/g, "/")).getTime()-nowDay;
                var endDiffToday = new Date(orderInfo.endDate.replace(/-/g, "/")).getTime()-nowDay;
                // 当前日期在入住和离店日期内，且不是在退款中
                if (((startDiffToday == endDiffToday) || (endDiffToday >= 0 && startDiffToday <= 0)) && currentOrderRefundStatus !== orderRefundStatusConstant.applying) {
                    $('#orderCheckin').removeClass('hidden');
                } else {
                    $('#orderCheckin').addClass('hidden');
                    orderCheckin.addClass('hidden');
                }

                // 订单为已支付，且未申请过退款
                if (currentOrderRefundStatus === orderRefundStatusConstant.default && currentOrderStatus == orderStatusConstant.paied) {
                    $('#orderRefund').closest('div').removeClass('hidden');
                    $('#refundModal .order-refund-rule').html(orderInfo.refundRule);
                } else {
                    $('#orderRefund').closest('div').addClass('hidden');
                }
                var fillIdentity = $('.fillIdentity');
                if(orderInfo.checkinAllEnable){
                    $('#orderCheckin').addClass('hidden');
                    for(var i=0;i<orderCheckin.length;i++){
                        if(!orderCheckin.eq(i).hasClass('hidden')){
                            $('.line-check-prompt').removeClass('hidden');
                        }
                    }  
                    orderCheckin.closest('.order-status-container .orderCheckin').addClass('hidden');
                }else{
                    $('.line-check-prompt').addClass('hidden');
                    for(var i=0;i<orderCheckin.length;i++){
                        var checkinEnable = orderCheckin.eq(i).attr('checkinEnable');
                        if(checkinEnable == 'true'){
                            if(!orderCheckin.eq(i).hasClass('hidden')){
                                fillIdentity.eq(i).removeClass('hidden');
                                $('.line-check-id-prompt').removeClass('hidden');
                            }
                            orderCheckin.eq(i).addClass('hidden');
                            $('#orderCheckin').addClass('hidden');
                        }
                    }                                        
                };                
                break;
            case orderStatusConstant.checkined:
                if(isBookedUser == true){
                    orderCheckOutContainer.removeClass('hidden');
                    checkedRoomName.removeClass('hidden');
                    for(var i=0;i<orderCheckin.length;i++){
                        var canGetCard = orderCheckin.eq(i).attr('canGetCard');
                        var status = orderCheckin.eq(i).attr('status');
                        if(status == orderStatusConstant.checkined){
                            if(canGetCard == 1){
                                orderRoomCard.eq(i).removeClass('hidden');
                            }else{
                                noOrderRoomCard.eq(i).removeClass('hidden');
                            }                            
                        }

                        if(status== orderStatusConstant.checkined){
                            checkedRoomName.eq(i).find('input').attr({'disabled':false,'checked':true});
                            checkedRoomName.eq(i).find('.roomName').removeClass('roomNameNoCheck');
                        }else{
                            checkedRoomName.eq(i).find('input').attr({'disabled':true,'checked':false});
                        }                          
                    }        
                }else{
                    for(var i=0;i<orderCheckin.length;i++){
                        var canGetCard = orderCheckin.eq(i).attr('canGetCard');
                        var UserId = orderCheckin.eq(i).attr('bookUserId');
                        var status = orderCheckin.eq(i).attr('status');
                        if(orderInfo.currentUserId == UserId && status== orderStatusConstant.checkined){
                            orderCheckOutContainer.removeClass('hidden');
                            if(canGetCard == 1){
                                orderRoomCard.eq(i).removeClass('hidden');
                            }else{
                                noOrderRoomCard.eq(i).removeClass('hidden');
                            }
                            checkedRoomName.eq(i).removeClass('hidden').find('input').attr({'checked':true});
                            break;
                        }
                    }                    
                }
                documentBody.find('.order-status').addClass('active');
                break;
            case orderStatusConstant.needOut:
                if(isBookedUser == true){
                    orderCheckOutContainer.removeClass('hidden');
                    checkedRoomName.removeClass('hidden');
                    for(var i=0;i<orderCheckin.length;i++){
                        if(status== orderStatusConstant.needOut){
                            checkedRoomName.eq(i).find('input').attr({'disabled':false,'checked':true});
                            checkedRoomName.eq(i).find('.roomName').removeClass('roomNameNoCheck');
                        }else{
                            checkedRoomName.eq(i).find('input').attr({'disabled':true,'checked':false});
                        }                          
                    }        
                }else{
                    for(var i=0;i<orderCheckin.length;i++){
                        var UserId = orderCheckin.eq(i).attr('bookUserId');
                        var status = orderCheckin.eq(i).attr('status');
                        if(orderInfo.currentUserId == UserId && status== orderStatusConstant.needOut){
                            checkedRoomName.eq(i).removeClass('hidden').find('input').attr({'checked':true});
                            break;
                        }
                    }                    
                }            
                break;
            default:
                documentBody.find('.order-status').addClass('disabled');
                break;
        }
        
    };
    var requireLoginErrorHandler = function (error) {
        toggleLoading(false);
        if (typeof error.responseJSON === 'undefined') {
            toastr.error(lang('tip.system'));
            return;
        }

        if (error.responseJSON.status === 304) {
            $('#order-list-toggle').addClass('hidden');
            $('#doc-body').addClass('hidden');
            $('#doc-content').removeClass('hidden');
            return;
        }
        toastr.error(error.responseJSON.info);
    };

    var commonErrorHandler = function (error) {
        toggleLoading(false);
        toastr.error(typeof error.responseJSON === 'undefined' ? lang('tip.system') : error.responseJSON.info);
    };

    var requestOrderInfo = function () {
        toggleLoading(true);
        ajaxRequest('/Home/Order/detail', {
            'orderNumber': orderNumber
        }, 'post', function (data) {
            toggleLoading(false);   
            window.currentOrder = data.data;
            refreshDocument(window.currentOrder);
            // 取消订单
            $('#submitCancel').on('click', function (e) {
                $('#addRoomInfoHTML').html('');
                toggleLoading(true);
                var submitBtn = $(this);
                ajaxRequest('/Home/Order/cancel', {
                    'orderNumber': orderNumber,
                    'bookPerson':window.currentOrder.bookPerson
                }, 'post', function (data) {
                    toggleLoading(false);
                    var user = window.currentOrder.user;
                    for(var i=0;i<user.length;i++){
                        user[i].status = orderStatusConstant.cancelled;
                    }
                    refreshDocument(window.currentOrder);
                    $('#cancelModal').modal('hide');
                }, commonErrorHandler, submitBtn);
            });
            // 确定全部入住
            $('#orderCheckin').on('click', function (e) {
                $('#addRoomInfoHTML').html('');
                toggleLoading(true);
                var submitBtn = $(this);
                var orderRoomId = submitBtn.data("orderRoomId"); 
                ajaxRequest('/Home/Order/checkin', {
                    'bookPerson':1,
                    'orderRoomId':orderRoomId,
                    'bookUserId':window.currentOrder.currentUserId
                }, 'post', function (data) {
                    toggleLoading(false);
                    var user = window.currentOrder.user;
                    for(var i=0;i<user.length;i++){
                        if(user[i].status == orderStatusConstant.paied){
                            user[i].status = orderStatusConstant.checkined;
                            user[i].statusName = lang('status.checkIn');
                        }
                    }
                    refreshDocument(window.currentOrder);
                }, commonErrorHandler, submitBtn);
            });
            //单独入住
            $('#doc-body').on('click','.orderCheckin',function(){
                $('#addRoomInfoHTML').html('');
                toggleLoading(true);                
                var submitBtn = $(this);
                var orderRoomId = [submitBtn.attr('room')];
                var index = submitBtn.attr('index');
                var isBookPerson = '';
                if(window.currentOrder.currentUserId == window.currentOrder.bookPerson){
                    isBookPerson = 1;
                }else{
                    isBookPerson = 0;
                };
                ajaxRequest('/Home/Order/checkin', {
                    'bookPerson':isBookPerson,
                    'orderRoomId':orderRoomId,
                    'bookUserId':window.currentOrder.currentUserId
                }, 'post', function (data) {
                    toggleLoading(false);
                    var user = window.currentOrder.user;
                    if(user[index].status == orderStatusConstant.paied){
                        user[index].status = orderStatusConstant.checkined;
                        user[index].statusName = lang('status.checkIn');
                    }
                    refreshDocument(window.currentOrder);
                }, commonErrorHandler, submitBtn);                
            });
            // 申请退款
            $('#submitRefund').on('click', function (e) {
                $('#addRoomInfoHTML').html('');
                var reason = $('#requestRefundReason').val().trim();
                if (reason === '' || reason.length > 255) {
                    toastr.error(lang('requestRefundReason'));
                    return;
                }
                toggleLoading(true);
                var submitBtn = $(this);
                ajaxRequest('/Home/Order/refund', {
                    'orderNumber': orderNumber,
                    'reason': reason,
                    'bookPerson':window.currentOrder.bookPerson
                }, 'post', function (data) {
                    toggleLoading(false);
                    window.currentOrder.refundStatus = orderRefundStatusConstant.applying;
                    refreshDocument(window.currentOrder);
                    $('#refundModal').modal('hide');
                }, commonErrorHandler, submitBtn);
            });           
            // 确定退房
            $('#submitCheckOut').on('click', function (e) {
                $('#addRoomInfoHTML').html('');
                var submitBtn = $(this);
                var checkedRoomName = $('.addLabel');
                var orderRoomId = [];
                var index=[];
                for(var i=0;i<checkedRoomName.length;i++){
                    var checked = checkedRoomName.eq(i).find('input');             
                    if(checked.is(':checked')){
                        orderRoomId.push(checked.attr('room'));
                        index.push(parseInt(checked.attr('index')));
                    }
                }
                if(index.length<1){
                    toastr.error(lang('requestRoom'));
                    return;
                }
                toggleLoading(true);
                var isBookPerson = '';
                if(window.currentOrder.currentUserId == window.currentOrder.bookPerson){
                    isBookPerson = 1;
                }else{
                    isBookPerson = 0;
                };           
                ajaxRequest('/Home/Order/checkout', {
                    'bookPerson':isBookPerson,
                    'bookUserId':window.currentOrder.currentUserId,
                    'orderRoomId':orderRoomId
                }, 'post', function (data) {
                    toggleLoading(false);
                    var user = window.currentOrder.user;
                    for(var i=0;i<user.length;i++){
                        for(var j=0;j<index.length;j++){
                            if(i == index[j]){
                               user[i].status = orderStatusConstant.checkouted; 
                            }
                        }
                    }
                    refreshDocument(window.currentOrder);
                    $('#checkOutModal').modal('hide');
                }, commonErrorHandler, submitBtn);
            });
        }, requireLoginErrorHandler);
    };
    requestOrderInfo();
    
    //身份证
    var idCardChangeModal = $('#idCardChangeModal');
    window.face = '';
    window.back = '';
    $('#doc-body').on('click','.fillIdentity',function(){
        idCardChangeModal.modal('show');
        idCardChangeModal.data('id',$(this).attr('orderuserid'));
    });
    idCardChangeModal.on('click','.header-cancel', function (e) {
        e.preventDefault();
        e.stopPropagation();
        idCardChangeModal.modal('hide');
        $('.get-photo').removeClass('hidden');
        $('.add-photo').addClass('hidden').html(''); 
        $("input[type='file']").val('');
        window.face = '';
        window.back = '';
    });
    $('#submitEditIdCard').on('click',function(e){
        var orderUserId = idCardChangeModal.data('id');
        if(window.face == ''){
            toastr.error(lang('select.pic'));
            return false;
        }
        e.preventDefault();
        e.stopPropagation();
        Parmas = {};
        Parmas.baseface = window.face;
        if(window.back != ''){
            Parmas.baseback = window.back;
        }
        toggleLoading(true); 
        ajaxRequest('/Home/User/getIdInformation', Parmas, 'post',function(data){
            var info = data.data;
            if(info.sex == lang('male')){
                var sex = 1;
            }else{
                var sex = 0;
            }
            toggleLoading(false);
            ajaxRequest('/Home/Order/saveOrder', {
                'hotel': currentHotel,
                'orderUserId': orderUserId,
                'identity':info.num,
                'name':info.name,
                'idsex':sex,
                'idnation':info.nationality,
                'idaddress':info.address
            }, 'post', function (data) {
                window.location.reload();
            }, commonErrorHandler);
        }, function(error) {
            toggleLoading(false); 
            toastr.error(typeof error.responseJSON === 'undefined' ? lang('tip.server') : error.responseJSON.info);
        }); 
    });    
    
    $("input[type='file']").on('change', function (e) {  
        var self = $(this);  
        var file = e.target.files[0];
        drawOnCanvas(file,self);        
    }); 
    function drawOnCanvas(file,self) {
        var reader = new FileReader();
        var cameraContainer = self.closest('.camera-container');
        var value = cameraContainer.data('value');
        var width = cameraContainer.width();
        var height = cameraContainer.height();
        reader.onload = function(e) {
            var dataURL = e.target.result,
            canvas = document.querySelector('canvas'),
            ctx = canvas.getContext('2d'),
            img = new Image();
            img.onload = function() {
                var square = 320;
                canvas.width = square;
                canvas.height = square;
                var context = canvas.getContext('2d');
                context.clearRect(0, 0, square, square);
                var imageWidth;
                var imageHeight;
                var offsetX = 0;
                var offsetY = 0;
                if (this.width > this.height) {
                    imageWidth = Math.round(square * this.width / this.height);
                    imageHeight = square;
                    offsetX = -Math.round((imageWidth - square) / 2);
                } else {
                    imageHeight = Math.round(square * this.height / this.width);
                    imageWidth = square;
                    offsetY = -Math.round((imageHeight - square) / 2);
                }
                context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight);
                var base64 = canvas.toDataURL('image/jpeg', 0.7);
                if(parseInt(value) == 1){
                   window.face = base64; 
                }else{
                    window.back = base64;
                }
                cameraContainer.find('.get-photo').addClass('hidden');
                cameraContainer.find('.add-photo').removeClass('hidden').append(img);
                cameraContainer.find('img').css({'width':width,'height':height});
            };
            img.src = dataURL;
        };
        reader.readAsDataURL(file);
    };        
});
